<template>
  <div class="queryform-container">
    <a-form ref="queryFormRef" :model="queryForm" layout="inline">
      <a-form-item :label-col="{ span: 6 }"
                   :wrapper-col="{ span: 16 }" autocomplete="off"
                   label="角色名"
                   name="roleName">
        <a-input v-model:value="queryForm.roleName" allow-clear/>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="handleQuery">查询</a-button>
        <a-button class="split-button" type="primary" @click="handleReset">重置</a-button>
      </a-form-item>
    </a-form>
  </div>
  <div class="action-buttons-container">
    <a-button type="primary" class="split-button" @click="handleOpenAddModel(false)">新增</a-button>
    <a-button type="primary" class="split-button" :disabled="!singleSelect" @click="handleOpenAddModel(true)">修改
    </a-button>
  </div>
  <a-table rowKey="id" :row-selection="rowSelection" :data-source="list" :columns="columns">
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'action'">
        <a-button @click="openRoleMenuDiag(record)">设置权限</a-button>
      </template>
    </template>
  </a-table>
  <a-modal v-model:visible="showAddModel" title="新增或修改用户" @ok="handleSave">
    <a-form ref="addForm" :model="addForm"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }" autocomplete="off">
      <a-form-item style="display: none;"
                   label="id"
                   name="id">
        <a-input v-model:value="addForm.id"/>
      </a-form-item>
      <a-form-item
          label="角色名"
          name="roleName"
          :rules="[{ required: true, message: 'Please input your roleName!' }]"
      >
        <a-input v-model:value="addForm.roleName"/>
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal title="设置权限" v-model:visible="showRoleMenuModel" @ok="handleSaveRoleMenu">
    <a-tree
        v-model:checkedKeys="selectedMenuKeys"
        :fieldNames="{children:'children', title:'menuName', key: 'menuCode' }"
        checkable
        defaultExpandAll
        :checkStrictly="true"
        :tree-data="sysMenuList"
    >
    </a-tree>
  </a-modal>
</template>
<script>
import request from "@/util/request.js";
import {message} from 'ant-design-vue';
import {showLoading,hideLoading} from "@/util/util.js";
export default {
  data() {
    return {
      selectedMenuKeys: [],
      showAddModel: false,
      showRoleMenuModel: false,
      list: [],
      columns: [{
        title: '角色名',
        dataIndex: 'roleName',
        key: 'roleName'
      }, {
        title: '操作',
        dataIndex: 'action',
        key: 'action'
      }],
      addForm: {id: null, roleName: 'asdfasdf'},
      selectedRows: [],
      singleSelect: false,
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
          this.selectedRows = selectedRows
          this.singleSelect = this.selectedRows && this.selectedRows.length === 1;
        },
        // getCheckboxProps: record => ({
        //   disabled: record.name === 'Disabled User',
        //   // Column configuration not to be checked
        //   name: record.name,
        // }),
      },
      queryForm: {roleName: null},
      sysMenuList: [],
      roleMenuSelectedRole: null,
    }
  },
  mounted() {
    this.query()
  },
  methods: {
    handleSaveRoleMenu() {
      let roleCode = this.roleMenuSelectedRole.roleCode;
      let data = []
      console.log(this.selectedMenuKeys)
      for (let menuKey of this.selectedMenuKeys.checked) {
        data.push({
          roleCode: roleCode,
          menuCode: menuKey,
        })
      }
      //保存此次设置
      request({
        url: '/api/system/sysRoleMenu/setByRole?roleCode=' + roleCode,
        method: 'post',
        data: data
      }).then((response) => {
        if (response.code === 200) {
          message.success("保存成功")
          this.showRoleMenuModel = false
        } else {
          message.error("保存失败")
        }
      })
    },
    async openRoleMenuDiag(row) {
      this.sysMenuList = []
      this.selectedMenuKeys = []
      this.roleMenuSelectedRole = row
      //加载角色列表，按照树形展示
      let response = await request({
        method: 'post',
        url: '/api/system/sysmenu/loadPermissionTree',
      })
      this.sysMenuList = response.data;
      this.showRoleMenuModel = true
      response = await request({
        method: 'post',
        url: '/api/system/sysRoleMenu/loadByRoleCode?roleCode=' + row.roleCode,
      })
      let roleMenuList = response.data
      let menuCodes = roleMenuList.map(rm => rm.menuCode);
      this.selectedMenuKeys = {checked: menuCodes};
    },
    handleQuery() {
      this.query(this.queryForm)
    },
    handleReset() {
      this.$refs.queryFormRef.resetFields()
    },
    query(param) {
      showLoading()
      request({
        method: 'post',
        url: '/api/system/sysRole/list',
        data: param || {}
      }).then((res) => {
        hideLoading()
        this.list = res.data
      })
    },
    handleOpenAddModel(editing) {
      this.showAddModel = true
      this.addForm = {}
      if (editing) {
        this.$nextTick(() => {
              //加载明细
              let selectedRow = this.selectedRows[0];
              this.addForm = {...selectedRow};
            }
        )
      }
    },
    handleSave() {
      let addForm = this.$refs.addForm;
      addForm.validate().then((res) => {
        showLoading()
        request({
          method: 'post',
          url: '/api/system/sysRole/saveOrUpdate',
          data: res
        }).then((res) => {
          hideLoading()
          if (res.code === 200) {
            this.showAddModel = false;
            message.success("保存成功")
            this.query();
          } else {
            message.error("操作失败" + res.errMsg)
          }
        })
      }).catch(() => {
        hideLoading()
      })
    },
  }
}
</script>
